const sessionStorage = window.sessionStorage

export const interceptor = function (Vue) {
  Vue.http.interceptors.push((request, next) => {
    let tokenVal = sessionStorage.getItem('token')
    if (tokenVal) {
      request.headers['token'] = tokenVal
    }

    next((response) => {
      let status = response.status
      let data = response.data
      try {
        if (typeof data === 'string') {
          data = JSON.parse(data)
        }
      } catch (e) {

      }
      let options = {
        message: ''
      }
      if (status === 401) {
        window.location.href = '/login'
      } else if (status === 500) {
        this.$toast.center('loading')
      } else if (status === 200) {
        if (response.data['<isError>']) {
          options.title = ' '
          options.desc = `${data.message} `
          this.$toast.center(options)
        } else if (data.data && data.data['ecode'] === '401') { // timeout
          options.desc = data.data['msg'] || 'Timeout...'
          options.duration = 3
          options.key = 'timeout-error'
          window.location.href = '/login'
          this.$toast.center(options)
        }
      }
      // isError && Message.error(options)
      // return response
    })
  })
}
